<?php
class WeatherApi extends Api
{
	protected $_locationUrl = 'http://61.4.185.48:81/g/';
	protected $_weatherUrlRealTime = 'http://www.weather.com.cn/data/sk/%s.html';
	protected $_weatherUrl = 'http://m.weather.com.cn/data/%s.html';
	protected $_ttl = 43200;
	
	protected function _get($url, $location="")
	{
		if (empty($location)) {
			$location = $this->getLocation();
		} 
		$cache_id = 'weather-' . $location;
		$ttl = $this->_ttl;
		$weather = ayw_get_cache($cache_id, $ttl);
		if (empty($weather)) {
			$weatherUrl = sprintf($url, $location);
			require_cache('./addons/libs/Http.class.php');
			$data = Http::get($weatherUrl);
			if ($data) {
				$data = json_decode($data);
			}
			$weather = (array)$data->weatherinfo;
			ayw_set_cache($cache_id, $weather, $ttl);
		}
		return $weather;
	}		
	
	public function getRealtime($location="")
	{
		return $this->_get($this->_weatherUrlRealTime);
	}	
	
	public function getOneWeek($location="")
	{
		return $this->_get($this->_weatherUrl);
	}
	
	public function getLocation()
	{
		$cache_id = 'location-' . $_SERVER['REMOTE_ADDR'] ;
		$ttl = $this->_ttl;
		$location = ayw_get_cache($cache_id, $ttl);
		if (empty($location)) {
			require_cache('./addons/libs/Http.class.php');
			$data = Http::get($this->_locationUrl);
			$pattern = '/id=(\d+)/';
			preg_match($pattern, $data, $result);
			if (empty($result[1])) {
				return '101010100';
			} else {
				ayw_set_cache($cache_id, $result[1], $ttl);
				return $result[1];
			}
		} else {
			return $location;
		}
	}
	
}